import { Button, Form, Input, Modal, message } from 'antd';
import axios from 'axios';
import React, { Component, useRef } from 'react';

class PersonCenter extends Component {
    userFormRef = React.createRef();

    state = {
        saveUserModal: false
    }

    componentDidMount() {
        const user = JSON.parse(localStorage.getItem('user'))
        this.setState({ saveUserModal: user.address ? false : true })
    }


    savaUserInfo = (values) => {
        const user = JSON.parse(localStorage.getItem('user'))
        values.id = user.id
        console.log(values);
        axios.post('/shopping-user-server/user/saveInfo', values)
            .then(response => {
                const resp = response.data
                if (resp.success) {
                    message.success(JSON.stringify(resp.data))
                } else {
                    message.error(JSON.stringify(resp.data))
                }
            }).catch(error => {
                message.error(error)
            });
    }
    render() {
        const t = localStorage.getItem("token")
        if (!t) { message.info('未登录,1秒后跳转登录'); setTimeout(() => location.href = '/login', 1000); return }

        const user = JSON.parse(localStorage.getItem('user'))
        const modalOk = () => {
            this.userFormRef.current.submit();
            this.setState({
                saveUserModal: true
            })
        }
        return (
            <div>
                {!user.address && <Button>去填写我的收货地址</Button>}
                <h1>{user.nickname}</h1>
                <Modal
                    onOk={modalOk}
                    cancelText={'下次再说'}
                    onCancel={() => [this.setState({ saveUserModal: false })]}
                    open={this.state.saveUserModal}>
                    <Form
                        ref={this.userFormRef}
                        onFinish={this.savaUserInfo}>
                        <Form.Item
                            initialValue={user.nickname}
                            name={'nickname'}
                            label={'昵称'}>
                            <Input></Input>
                        </Form.Item>
                        <Form.Item
                            name={'phone'}
                            initialValue={user.phone}
                            label={'手机号'}>
                            <Input></Input>
                        </Form.Item>
                        <Form.Item
                            name={'address'}
                            initialValue={user.address}
                            label={'收货地址'}>
                            <Input></Input>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default PersonCenter;